package com.zz.framework.core.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DownloadManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.media.AudioDeviceInfo
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.Display
import android.view.WindowManager
import android.view.WindowMetrics
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.FileProvider
import com.zz.framework.BuildConfig
import com.zz.framework.core.BaseApp
import com.zz.framework.core.ext.audioManager
import java.io.File


/**
 * Copyright © 2024 zhun All rights reserved.
 * Created by Zha0Zhun on 2024/7/16 13:02.
 * @author: Zha0Zhun 1820022519@qq.com
 * @version: V1.0
 */
object DeviceUtils {
    fun getSerialCode(): String {
        if (BuildConfig.DEBUG) {
//            三星堆
//            return "SY2501000001"
//           return "SY2501000002"
//         湖广会馆
//            return "123456"
//            海螺沟
            return "SY2501000204"
        }else {
            val serial = Settings.Global.getString(AppGlobals.getApplication().contentResolver, "vendor.gsm.serial")
            return serial?:"123456"
        }
    }

    /**
     * 判断设备是否root
     * @return the boolean`true`: 是<br></br>`false`: 否
     */
    fun isDeviceRooted(): Boolean {
        val su = "su"
        val locations = arrayOf(
            "/system/bin/", "/system/xbin/", "/sbin/", "/system/sd/xbin/", "/system/bin/failsafe/",
            "/data/local/xbin/", "/data/local/bin/", "/data/local/"
        )
        for (location in locations) {
            if (File(location + su).exists()) {
                return true
            }
        }
        return false
    }

    /**
     * 获取设备系统版本号
     *
     * @return 设备系统版本号
     */
    fun getSDKVersion(): Int {
        return Build.VERSION.SDK_INT
    }


    /**
     * 获取设备AndroidID
     *
     * @return AndroidID
     */
    @SuppressLint("HardwareIds")
    fun getAndroidID(): String {
        return Settings.Secure.getString(BaseApp.context.contentResolver, Settings.Secure.ANDROID_ID)
    }


    /**
     * 获取设备厂商
     * 如Xiaomi
     *
     * @return 设备厂商
     */
    fun getManufacturer(): String {
        return Build.MANUFACTURER
    }

    /**
     * 获取设备型号
     * 如MI2SC
     * @return 设备型号
     */
    fun getModel(): String {
        var model = Build.MODEL
        model = model?.trim { it <= ' ' }?.replace("\\s*".toRegex(), "") ?: ""
        return model
    }

    /**
     * 获取包含状态栏的屏幕完整宽高
     * @param context 上下文对象
     * @return 包含屏幕宽度和高度的 Point 对象，x 为宽度，y 为高度
     */
    fun getScreenSize(context: Context): Point {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val realSize = Point()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowMetrics: WindowMetrics = windowManager.currentWindowMetrics
            val bounds = windowMetrics.bounds
            realSize.x = bounds.width()
            realSize.y = bounds.height()
        } else {
            val display: Display = windowManager.defaultDisplay
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                display.getRealSize(realSize)
            } else {
                @Suppress("DEPRECATION")
                display.getSize(realSize)
            }
        }
        return realSize
    }

    fun openBluetoothSettings(context: Context) {
        val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        context.startActivity(intent)
    }

    fun openBluetoothSettings(context: Activity, code: Int) {
        val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        context.startActivityForResult(intent, code)
    }

    fun openWifiSettings(context: Context) {
        val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
        context.startActivity(intent)
    }

    fun openSettings(context: Context) {
        val intent = Intent(Settings.ACTION_SETTINGS)
        context.startActivity(intent)
    }

    /**
     * 静默安装,需要root权限
     * @param apkPath String
     */
    fun silentInstall(apkPath: String) {
        val process = Runtime.getRuntime().exec("pm install -r $apkPath")
        process.waitFor()
    }

    fun downloadApk(url: String, context: Context, savePath: String) {
        val request = DownloadManager.Request(Uri.parse(url))
            .setTitle("下载更新")
            .setDescription("正在下载最新版本")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationUri(Uri.parse("file://$savePath"))
        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        downloadManager.enqueue(request)
    }

    fun installApk(context: Context, apkFile: File) {
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(FileProvider.getUriForFile(context, "${context.packageName}.provider", apkFile), "application/vnd.android.package-archive")
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
        }
        context.startActivity(intent)
    }

    fun installApkSlient(apkPath: String) {
        LogUtils.error("installApkSlient")
        LogUtils.error("file exists: ${File(apkPath).exists()}")
        val intent = Intent("com.hebs.action.SLIENT_INSTALL_APK")
        intent.putExtra("apk_path", apkPath)
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
        intent.setComponent(ComponentName("com.android.packageinstaller", "com.android.packageinstaller.TemporaryFileManager"))
        AppGlobals.getApplication().sendBroadcast(intent)
    }

    fun clearBluetooth() {
        val intent = Intent("com.hebs.CLEAR_BLUETOOTH")
        AppGlobals.getApplication().sendBroadcast(intent)
    }

    fun toggleAudioOutput() {
        val audioManager = AppGlobals.getApplication().audioManager
        // 获取当前外放状态
        val isSpeakerphoneOn = audioManager!!.isSpeakerphoneOn
        // 切换外放状态
        audioManager!!.isSpeakerphoneOn = !isSpeakerphoneOn
    }

    fun forceSpeakerOn() {
        val audioManager = AppGlobals.getApplication().getSystemService(Context.AUDIO_SERVICE) as AudioManager
        audioManager.isSpeakerphoneOn = true  // 开启扬声器
        audioManager.mode = AudioManager.MODE_NORMAL
    }

    fun forceHeadsetOn() {
        val audioManager = AppGlobals.getApplication().audioManager
        audioManager?.isSpeakerphoneOn = false  // 关闭扬声器
        audioManager?.mode = AudioManager.MODE_IN_COMMUNICATION
    }

    fun setMaxVolume() {
        val audioManager = AppGlobals.getApplication().audioManager
        // 设置为通话模式
        audioManager?.mode = AudioManager.MODE_IN_COMMUNICATION
        // 强制使用扬声器
        audioManager?.isSpeakerphoneOn = true
//        val maxVolume = audioManager?.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL)?:100000 // 获取最大音量
//        audioManager?.setStreamVolume(AudioManager.STREAM_VOICE_CALL, maxVolume, AudioManager.FLAG_SHOW_UI)
        // 设置最大音量
        val maxVolume = audioManager?.getStreamMaxVolume(AudioManager.STREAM_MUSIC)?:100000 // 获取最大音量
        audioManager?.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_SHOW_UI)
    }

    fun restoreOriginalVolume(originalVolume: Int) {
        val audioManager =  AppGlobals.getApplication().audioManager
        if (originalVolume >= 0) { // 确保之前记录了音量
            audioManager?.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, AudioManager.FLAG_SHOW_UI)
        }
    }
}